"""
直接获取文本选择的Python库演示
注意：大多数方案仍需要用户手动复制或使用系统API
"""

import pyperclip
import tkinter as tk
import subprocess
import platform
import time

# 方案1：使用pyperclip（推荐，跨平台）
def get_clipboard_text():
    """使用pyperclip获取剪贴板内容"""
    try:
        return pyperclip.paste()
    except Exception as e:
        print(f"获取剪贴板内容失败: {e}")
        return None

# 方案2：使用tkinter剪贴板
def get_clipboard_text_tkinter():
    """使用tkinter获取剪贴板内容"""
    try:
        root = tk.Tk()
        root.withdraw()  # 隐藏窗口
        text = root.clipboard_get()
        root.destroy()
        return text
    except Exception as e:
        print(f"获取剪贴板内容失败: {e}")
        return None

# 方案3：Linux系统使用xclip
def get_clipboard_text_linux():
    """Linux系统使用xclip获取剪贴板内容"""
    if platform.system() != "Linux":
        return None
    
    try:
        result = subprocess.run(['xclip', '-selection', 'clipboard', '-o'], 
                              capture_output=True, text=True, timeout=5)
        return result.stdout if result.returncode == 0 else None
    except Exception as e:
        print(f"xclip获取失败: {e}")
        return None

# 方案4：macOS系统使用pbpaste
def get_clipboard_text_macos():
    """macOS系统使用pbpaste获取剪贴板内容"""
    if platform.system() != "Darwin":
        return None
    
    try:
        result = subprocess.run(['pbpaste'], capture_output=True, text=True, timeout=5)
        return result.stdout if result.returncode == 0 else None
    except Exception as e:
        print(f"pbpaste获取失败: {e}")
        return None

# 方案5：Windows系统使用PowerShell
def get_clipboard_text_windows():
    """Windows系统使用PowerShell获取剪贴板内容"""
    if platform.system() != "Windows":
        return None
    
    try:
        ps_script = "Get-Clipboard"
        result = subprocess.run(['powershell', '-Command', ps_script], 
                              capture_output=True, text=True, timeout=5)
        return result.stdout.strip() if result.returncode == 0 else None
    except Exception as e:
        print(f"PowerShell获取失败: {e}")
        return None

# 综合方案：自动选择最佳方法
def get_clipboard_text_auto():
    """自动选择最佳方法获取剪贴板内容"""
    system = platform.system()
    
    # 优先使用pyperclip（跨平台）
    try:
        text = pyperclip.paste()
        if text:
            return text
    except:
        pass
    
    # 系统特定方法
    if system == "Linux":
        return get_clipboard_text_linux()
    elif system == "Darwin":  # macOS
        return get_clipboard_text_macos()
    elif system == "Windows":
        return get_clipboard_text_windows()
    
    return None

# 方案6：监听剪贴板变化（需要额外库）
def monitor_clipboard_changes():
    """监听剪贴板变化（需要安装watchdog库）"""
    try:
        from watchdog.observers import Observer
        from watchdog.events import FileSystemEventHandler
        import os
        import tempfile
        
        class ClipboardHandler(FileSystemEventHandler):
            def __init__(self, callback):
                self.callback = callback
                self.last_content = ""
            
            def on_modified(self, event):
                if not event.is_directory:
                    try:
                        current_content = get_clipboard_text_auto()
                        if current_content and current_content != self.last_content:
                            self.last_content = current_content
                            self.callback(current_content)
                    except:
                        pass
        
        # 创建临时目录监听
        temp_dir = tempfile.mkdtemp()
        handler = ClipboardHandler(lambda text: print(f"剪贴板变化: {text}"))
        observer = Observer()
        observer.schedule(handler, temp_dir, recursive=False)
        observer.start()
        
        return observer
    except ImportError:
        print("需要安装watchdog库: pip install watchdog")
        return None

# 演示函数
def demo_all_methods():
    """演示所有方法"""
    print("=== 剪贴板内容获取方法演示 ===")
    
    # 方法1：pyperclip
    print("1. pyperclip方法:")
    text1 = get_clipboard_text()
    print(f"   结果: {text1}")
    
    # 方法2：tkinter
    print("2. tkinter方法:")
    text2 = get_clipboard_text_tkinter()
    print(f"   结果: {text2}")
    
    # 方法3：系统特定方法
    print("3. 系统特定方法:")
    text3 = get_clipboard_text_auto()
    print(f"   结果: {text3}")
    
    # 方法4：Linux xclip
    if platform.system() == "Linux":
        print("4. Linux xclip方法:")
        text4 = get_clipboard_text_linux()
        print(f"   结果: {text4}")
    
    # 方法5：macOS pbpaste
    if platform.system() == "Darwin":
        print("4. macOS pbpaste方法:")
        text4 = get_clipboard_text_macos()
        print(f"   结果: {text4}")
    
    # 方法6：Windows PowerShell
    if platform.system() == "Windows":
        print("4. Windows PowerShell方法:")
        text4 = get_clipboard_text_windows()
        print(f"   结果: {text4}")

if __name__ == "__main__":
    demo_all_methods()
